/*
 * 版权所有 (c) 2022-2099 TBIT。保留所有权利。
 */

/*
 * 版权所有 (c) 2022-2099 TBIT。保留所有权利。
 */

package com.tbit.uqbike.client.controller;

import cn.hutool.core.bean.BeanUtil;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tbit.uqbike.client.constant.RedisConstant;
import com.tbit.uqbike.client.constant.enums.PopUpEffectType;
import com.tbit.uqbike.client.pojo.AdaccountPopUp;
import com.tbit.uqbike.client.pojo.Result;
import com.tbit.uqbike.client.pojo.RideLogDetails;

import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.pojo.vo.AdaccountPopUpVO;
import com.tbit.uqbike.client.remote.DataUtils;
import com.tbit.uqbike.client.service.AdaccountPopUpService;
import com.tbit.uqbike.client.service.RedisService;
import com.tbit.uqbike.client.service.RideLogService;
import com.tbit.uqbike.client.service.TokenService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;


/**
* 弹框广告
*
* @author yao
* @since 2024-03-28
*/
@Slf4j
@RestController
@RequestMapping("/adaccountPopUp")
@AllArgsConstructor
public class AdaccountPopUpController {


    private final AdaccountPopUpService adaccountPopUpService;

    private final TokenService tokenService;
    private final RideLogService rideLogService;
    private final RedisService redisService;

    /**
     * 获得弹框广告
     * @param accountId 区域id
     * @return 弹框广告
     */
    @GetMapping("/getByAccountId")
    public Result<List<AdaccountPopUpVO>> get(Integer accountId,String token){
        List<AdaccountPopUp> byAccountId = adaccountPopUpService.getByAccountId(accountId);
        long now = new Date().getTime();
        List<AdaccountPopUpVO> collect = byAccountId.stream().map((adaccountPopUp) -> {
            AdaccountPopUpVO vo = BeanUtil.copyProperties(adaccountPopUp, AdaccountPopUpVO.class);
            vo.setStatus(now);
            return vo;
        }).collect(Collectors.toList());
        User user = tokenService.getUser(token);
        // 判断用户属于的目标人群标签
        Set<String> userTags = getTargetTag(user.getUserId());
        // 过滤结果
        List<AdaccountPopUpVO> validAds = collect.stream().filter(x -> {
            JSONObject object = JSON.parseObject(x.getContent());
            // 根据弹窗广告的目标人群 字符串, 没配置默认弹全部
            String affectStr = Optional.ofNullable(object.get("affectStr")).orElse("0").toString();

            // 计算广告生效时间
            String startTime = Optional.ofNullable(object.get("startTime")).orElse("-1").toString();
            String endTime = Optional.ofNullable(object.get("endTime")).orElse("-1").toString();
            long expireSeconds = 0;
            if (Objects.equals(startTime,"-1") || Objects.equals(endTime,"-1")){
                expireSeconds = -1;
            }else {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                expireSeconds = LocalDateTimeUtil.between(LocalDateTime.parse(startTime,formatter), LocalDateTime.parse(endTime,formatter), ChronoUnit.SECONDS);
            }
            // 0 代表不限次数
            int validCount = Integer.parseInt(Optional.ofNullable(object.get("validCount")).orElse("0").toString());

            // 用户标签和广告目标人群标签有交集，才添加到结果集
            for (String userTag : userTags) {
                // 符合目标人群
                if ( affectStr.contains(userTag) || affectStr.contains("0") ){
                    // 记录用户弹窗次数
                    if (validCount > 0 && redisService.incr(String.format("%s:%s:%s",RedisConstant.UserPopUpCount,x.getId(),user.getUserId()),expireSeconds) > validCount){
                        log.warn("用户{}弹窗次数到达上限{}",user.getUserId(),validCount);
                        return false;
                    }
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList());
        return Result.success(validAds);
    }

    /**
     * 判断用户归属人群
     * @param userId 用户id
     * @return 归属标签列表
     */
    private Set<String> getTargetTag(Integer userId){
        Set<String> tagList = new HashSet<>();
        // 新用户 无完成支付的骑行订单
        Integer allRideCount = rideLogService.getRideCount(userId, -1);
        if (allRideCount == 0){
            tagList.add(PopUpEffectType.NEW_USER.getCode());
        }else { // 老用户
            tagList.add(PopUpEffectType.OLD_USER.getCode());
        }
        // 七日内订单
        Integer rideCountInSevenDays = rideLogService.getRideCount(userId, 7);
        // 7日新用户
        if (rideCountInSevenDays != 0 && (allRideCount - rideCountInSevenDays) == 0){
            tagList.add(PopUpEffectType.SEVEN_DAY_NEW_USER.getCode());
        }
        Integer rideCountInThirtyDays = rideLogService.getRideCount(userId, 30);
        // 30日新用户
        if (rideCountInThirtyDays!= 0 && (allRideCount - rideCountInThirtyDays) == 0){
            tagList.add(PopUpEffectType.MONTH_NEW_USER.getCode());
        }
        return tagList;
    }
}